----------------------
-- 创角相关逻辑
----------------------
local Config = require("Config")
local PlayerNamesExcel = require("excel.playerNames")
local CommonDB = require("common.CommonDB")
local Lang = require("common.Lang")
local FilterUtil = require("common.FilterUtil")
local Log = require("common.Log")
local LogDefine = require("common.LogDefine")
local CommonDefine = require("common.CommonDefine")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local RoleDBLogic = require("role.RoleDBLogic")
local RoleHeadLogic = require("role.RoleHeadLogic")
local Broadcast = require("broadcast.Broadcast")
local RoleExcel = require("excel.role") 
local ReportManager = require("platform.ReportManager")
local HeroLogic = require("hero.HeroLogic")
local RelationGiftLogic = require("present.RelationGiftLogic")
local CombatDefine = require("combat.CombatDefine")
local CombatPosLogic = require("combat.CombatPosLogic")
local SysParameter = require("common.SysParameter")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local MailExcel = require("excel.mail")
local MailManager = require("mail.MailManager")

local ROLE_NAME_LEN_MAX = 21
local ROLE_NAME_LEN_MIN = 5
local OP_RET_SUCC = 1
local OP_RET_FAIL = 0

-- 生成一个11位的全局不重复的数字组成的id 
-- 规则 前6位服务器index 后五位自增id
function genIdentity()
	local firstStr= Config.SVR_INDEX
	local nowMax = CommonDB.getIdentityMax()
	nowMax = nowMax + 1
	CommonDB.setIdentityMax(nowMax)
	return firstStr .. "" .. nowMax	
end

function getFakeIdentityMax()
	local firstStr= Config.SVR_INDEX
	local id = CommonDB.getFakeIdentityMax()
	return firstStr .. string.format("%05d", id)	
end

local function checkRoleName(roleName, default)
	--如果roleName是nil   游戏名不能为空
	if not roleName then 
		return false, Lang.CREATE_ROLE_FAIL_NAME_NIL
	end
	local nameLen = string.len(roleName)
	--如果游戏名长度小于游戏名最小长度  角色名过短
	if nameLen < ROLE_NAME_LEN_MIN then
		return false, Lang.CREATE_ROLE_FAIL_NAME_LEN1
    end

	--如果游戏名长度大于游戏名最小长度  角色名过长
	if nameLen > ROLE_NAME_LEN_MAX then
		return false, Lang.CREATE_ROLE_FAIL_NAME_LEN2
    end
    
	if default == nil then
		--如果游戏名中包含非法字符				角色名中有非法字符
		if roleName ~= FilterUtil.filterName(roleName) then
			return false, Lang.CREATE_ROLE_FAIL_NAME_FILTER
		end
	end
	--角色名已经存在
	if RoleDBLogic.isNameExistInDB(roleName) then
		return false, Lang.CREATE_ROLE_FAIL_NAME_DUPLICATE
	end
	return true
end

function creatFakeDb(account)
    local db = RoleDBLogic.createDefaultRole(account)	
    local identity = genIdentity()
	db.identity = identity	
    db.name = account
    return db
end


function createNewRole(human)
	if _G.is_middle == true then
		return
	end
	
	if human.db or RoleDBLogic.isAccountExistInDB(human.account) then
		assert(nil)
		return
	end
	
	human.db = RoleDBLogic.createDefaultRole(human.account)	
	
	-- 保存数据
	human.db.name = human.account
	local identity = genIdentity()
	human.db.identity = identity

    -- 测试  临时增加，用于防沉迷测试
    human.db.age = 20
    ----------

    RelationGiftLogic.relationCreate(human)
	ObjHuman.initHuman(human)

	ObjHuman.save(human)
	ObjHuman.onLogin(human, true)
    createRoleSettingUp(human)

	ReportManager.register(human)
end

-- 改名操作结果
CHANGE_NAME_RET_FAIL = 0 	-- 失败
CHANGE_NAME_RET_OK = 1 		-- 成功，首次改名
CHANGE_NAME_RET_OK2 = 2 	-- 成功，非首次改名

CHANGE_NAME_COST = 200
function changeName(human, roleName)
	local msgRet = Msg.gc.GC_ROLE_CHANGE_NAME
	msgRet.ret = CHANGE_NAME_RET_FAIL
	local isOk, tip = checkRoleName(roleName)
	if not isOk then
		msgRet.tip = tip
		Msg.send(msgRet, human.fd)
		return
	end
	
	if not human.db.changeNameCnt then
		human.db.changeNameCnt = 1
	else
		if human.db.zuanshi < CHANGE_NAME_COST then
			msgRet.tip = Lang.COMMON_NO_ZUANSHI
			Msg.send(msgRet, human.fd)
			return
		end
		human.db.changeNameCnt = human.db.changeNameCnt + 1
		ObjHuman.decZuanshi(human, -CHANGE_NAME_COST, "change_name")
	end
    ObjHuman.onlineHuman[human.db.name] = nil
    ObjHuman.onlineHuman[roleName] = human

	human.db.name = roleName
	ObjHuman.save(human)

	msgRet.ret = CHANGE_NAME_RET_OK
	if human.db.changeNameCnt > 1 then
		msgRet.ret = CHANGE_NAME_RET_OK2
	end
	msgRet.tip = "ok"
	Msg.send(msgRet, human.fd)
    	
	if human.db.changeNameCnt == 1 then
		Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.account, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		ReportManager.create(human)
		Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.account, human.db.name, human.db.lv, human.db.ip)		
	end
end

-- 改名查询
function changeNameQuery(human)
	local msgRet = Msg.gc.GC_ROLE_CHANGE_NAME_QUERY
	if human.db.changeNameCnt == nil then
		msgRet.price = 0
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.SHOW_NAME_PANEL, human.db.ip,human.pf or "",human.appid, human.phpChanelID)		
	else
		msgRet.price = CHANGE_NAME_COST
	end
	Msg.send(msgRet,human.fd)
end

function randomName(human, sex)
	local msgRet = Msg.gc.GC_ROLE_RANDOM_NAME
	msgRet.sex = sex
	msgRet.name = getRandomName(sex)
	Msg.send(msgRet, human.fd)
end

function getRandomName(sex)
	if not sex then
		sex = math.random(1, 2)
	end
	local random1 = math.random(1, #PlayerNamesExcel.xing) 
	if sex == 1 then
		local random2 = math.random(1, #PlayerNamesExcel.name)
		return PlayerNamesExcel.xing[random1].xing..PlayerNamesExcel.name[random2].name
	else
		local random2 = math.random(1, #PlayerNamesExcel.name2)
		return PlayerNamesExcel.xing[random1].xing..PlayerNamesExcel.name2[random2].name
	end
end

-- 创角时修改角色信息
function createRoleChangeInfo(human,name,sex,firendCode)
    local msgRet = Msg.gc.GC_ROLE_CREATE_ROLE_CHANGE_MSG

	local isOk = checkRoleName(name)
    if isOk == false then
        msgRet.ret = 1
        Msg.send(msgRet,human.fd)
        return
    end

    -- 创角
    if not human.db.changeNameCnt then
		human.db.changeNameCnt = 0
	else
		if human.db.zuanshi < CHANGE_NAME_COST then
			msgRet.ret = 1
			Msg.send(msgRet, human.fd)
			return
		end
		human.db.changeNameCnt = human.db.changeNameCnt + 1
		ObjHuman.decZuanshi(human, -CHANGE_NAME_COST, "change_name")
	end

    ObjHuman.onlineHuman[human.db.name] = nil
    ObjHuman.onlineHuman[name] = human

	human.db.name = name
    human.db.sex = sex
    
    RoleHeadLogic.setHead(human, sex, RoleHeadLogic.HEAD_TYPE_1)
	ObjHuman.save(human)
    
    ChatPaoMaLogic.loginTips(human)

    -- 好友推荐  todo
    RelationGiftLogic.relationBind(human, firendCode)
    msgRet.ret = 0
    Msg.send(msgRet,human.fd)

    -- 记录流失日志
    if human.db.changeNameCnt == 0 then
		Log.write(Log.LOGID_OSS_REGISTER, human.db._id, human.db.account, human.db.name, human.ip,human.pf or "",human.appid, human.db.changeNameCnt)
		Log.write(Log.LOGID_OSS_CREATELOSS,human.db.account, human.db.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, human.db.ip,human.pf or "",human.appid, human.phpChanelID)
		ReportManager.create(human)
		Log.write(Log.LOGID_OSS_LOGIN, human.db._id, human.db.account, human.db.name, human.db.lv, human.db.ip)		
	end
end


function createRoleSettingUp(human)
   -- 赠送新英雄 上阵
   local heroId = SysParameter.getSysParameter(SysParameter.PARAMETER_8)
   if heroId and heroId ~= 0 then
      local bagIndex, uuid = HeroLogic.addHero(human, heroId,nil, 1, "create_role")
      if bagIndex and uuid and type(uuid) == "string" then
         local msg = {}
         msg.type = CombatDefine.COMBAT_TYPE1
         msg.formation = 1
         msg.heroList = "0,"..uuid
         msg.helpList = ""
         msg.jibanList = ""
         CombatPosLogic.updatePos(human, msg)
      end
   end
end



RANDOM_HEAD_ID_TABLE = nil
function getRandomHead()
	if RANDOM_HEAD_ID_TABLE == nil then
		RANDOM_HEAD_ID_TABLE = {}
		for k, v in pairs(RoleExcel.head) do
			RANDOM_HEAD_ID_TABLE[#RANDOM_HEAD_ID_TABLE + 1] = k
		end
	end

	local index = math.random(1, #RANDOM_HEAD_ID_TABLE)
	return RANDOM_HEAD_ID_TABLE[index]
end

RANDOM_BODY_ID_TABLE = nil
function getRandomBody()
	if RANDOM_BODY_ID_TABLE == nil then
		RANDOM_BODY_ID_TABLE = {}
		for k, v in pairs(RoleExcel.body) do
			RANDOM_BODY_ID_TABLE[#RANDOM_BODY_ID_TABLE + 1] = k
		end
	end

	local index = math.random(1, #RANDOM_BODY_ID_TABLE)
	return RANDOM_BODY_ID_TABLE[index]
end